package com.kizuki.thread;

import java.util.concurrent.TimeUnit;

public class TestDeadLock {

    /**
     * 死锁解决方法 终端命令
     * 1. jps 找到执行的线程id
     * 2. jstack 线程id 找到线程死锁想要的什么资源
     */
    public static void main(String[] args) {
        final String data1 = "data1";
        final String data2 = "data2";

        new Thread(new MyThread(data1, data2)).start();
        new Thread(new MyThread(data2, data1)).start();
    }

}

class MyThread implements Runnable{
    private String data1;
    private String data2;

    public MyThread(String data1, String data2) {
        this.data1 = data1;
        this.data2 = data2;
    }

    @Override
    public void run() {
        synchronized (data1) {
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName() + "拥有：" + data1 + " 想要：" + data2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (data2){
                System.out.println(Thread.currentThread().getName() + "尝试获取" + data2);
            }
        }
    }



}
